# -*- coding: utf-8 -*-
"""
@Time ： 2025/2/12 15:22
@Auth ： 李天天
"""
import re
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import logging

from Common.handle_redis import RedisHelper

app = FastAPI()
do_redis = RedisHelper(host="10.10.118.92", port="6379", password="li123456")
# 配置日志
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")


# 定义短信数据模型
class SMSData(BaseModel):
    # phone: str  # 发送短信的手机号
    message: str  # 短信内容
    # received_at: str  # 短信接收时间（可选，SmsForwarder支持）


@app.post("/receive_sms/")
async def receive_sms(sms: SMSData):
    """接收 SmsForwarder 转发的短信"""
    # logging.info(f"收到短信: 来自 {sms.phone}, 内容: {sms.message}, 时间: {sms.received_at}")
    # print(f"收到短信: 来自 {sms.phone}, 内容: {sms.message}, 时间: {sms.received_at}")
    print(f"{sms.message}")
    text = sms.message
    # 匹配手机号
    phone_match = re.search(r"(?:\+86)?(\d{11})", text)
    phone_number = phone_match.group(1) if phone_match else None

    # 匹配验证码
    code_match = re.search(r"验证码：(\d{6})", text)
    verification_code = code_match.group(1) if code_match else None

    do_redis.set(key=f"{phone_number}", value=f"{verification_code}", ex="20")

    return {"status": "success", "message": "SMS received"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
